package IC.kafka.consumer;

import IC.kafka.remote.KafkaToesWarn;
import IC.kafka.utils.MsgUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ic.alarm.domain.WarnData;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.UUID;

@Component
@Log4j2
public class MqQueueConsumer {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private KafkaToesWarn kafkaToesWarn;

    @Autowired
    private MsgUtil msgUtil;

    private static final String QUEUE_TWO = "queue_two";

    private static final String TELEPHONE = "19153674426";

//    private static final String RADOM_CODE = RandomUtil.randomNumbers(6);
    private static final String RADOM_CODE = "您所布放的嫌疑人已出现";

    @RabbitListener(queuesToDeclare = @Queue(QUEUE_TWO))
    public void mqQueueConsumer(String msg, Message message, Channel channel) {
        log.info("接收到消息：{}", msg);
        WarnData warnData = JSONObject.parseObject(msg, WarnData.class);

        String messageId = message.getMessageProperties().getMessageId();
        try {
            Long added = redisTemplate.opsForSet().add(QUEUE_TWO, messageId);
            if (added != 0) { // 确保消息ID是新的，才处理消息
                kafkaToesWarn.instartWarn(warnData);
                String s = msgUtil.sendMsg(TELEPHONE, RADOM_CODE);
                if (s.contains("0")) {
                    log.info("发送成功");
                }
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                log.info("消息ID已存在，跳过处理");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (Exception e) {
            log.info("消息消费失败：{}", e.getMessage());
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false); // 根据需要决定是否重新入队
            } catch (Exception e1) {
                log.info("消息拒绝失败：{}", e1.getMessage());
            }
        }
    }
}
